<template>
  <view class="ai-chat-page" :class="{'expanded': messages.length > 0}">
    <!-- 空状态主页 -->
    <view class="empty-home" v-if="messages.length === 0">
      <view class="logo-container">
        <image src="/static/images/logo.png" class="big-logo"></image>
        <text class="slogan">我是DeepSeek，随时待命！</text>
      </view>
      
      <!-- 输入区域 -->
      <view class="input-area">
        <input 
          class="message-input" 
          type="text" 
          v-model="userMessage" 
          placeholder="给 DeepSeek 发消息"
          @confirm="sendMessage"
        />
        <button 
          class="send-button" 
          :disabled="isLoading || !userMessage.trim()" 
          @click="sendMessage"
        >
          <text>发送</text>
        </button>
      </view>
    </view>
    
    <!-- 对话区域 -->
    <view class="chat-container" v-else>
      <!-- 消息区域 -->
      <scroll-view scroll-y class="message-area" :scroll-top="scrollTop">
        <view v-for="(message, index) in messages" :key="index" class="message-item" :class="message.role">
          <view class="message-content">{{ message.content }}</view>
        </view>
      </scroll-view>
      
      <!-- 输入区域 -->
      <view class="input-area">
        <input 
          class="message-input" 
          type="text" 
          v-model="userMessage" 
          placeholder="给 DeepSeek 发消息"
          @confirm="sendMessage"
        />
        <button 
          class="send-button" 
          :disabled="isLoading || !userMessage.trim()" 
          @click="sendMessage"
        >
          <text>{{ isLoading ? '回复中' : '发送' }}</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'AiChat',
  data() {
    return {
      userMessage: '',
      messages: [],
      isLoading: false,
      scrollTop: 0,
      apiKey: 'app-BsHrk7wM6rKsrkAvCVDpBZyA'
    }
  },
  computed: {
    cloudStorage() {
      return this.$store.state.cloudStorage;
    }
  },
  watch: {
    // 监听消息数组变化，当从空变为有内容时，滚动页面到底部
    'messages.length': function(newVal, oldVal) {
      if (oldVal === 0 && newVal > 0) {
        this.$nextTick(() => {
          this.scrollPageToBottom();
        });
      }
    }
  },
  methods: {
    // 滚动页面到底部
    scrollPageToBottom() {
      // 使用uni-app的页面滚动API
      uni.pageScrollTo({
        scrollTop: 999999,
        duration: 300
      });
    },
    
    sendMessage() {
      if (!this.userMessage.trim() || this.isLoading) return;
      
      // 添加用户消息
      this.messages.push({
        role: 'user',
        content: this.userMessage
      });
      
      const query = this.userMessage;
      this.userMessage = '';
      
      this.getAIResponse(query);
      
      // 页面已展开时，确保滚动到底部
      if (this.messages.length > 1) {
        this.$nextTick(() => {
          this.scrollPageToBottom();
        });
      }
    },
    
    async getAIResponse(query) {
      this.isLoading = true;
      
      try {
        uni.request({
          url: 'https://api.dify.ai/v1/chat-messages',
          method: 'POST',
          header: {
            'Authorization': `Bearer app-BsHrk7wM6rKsrkAvCVDpBZyA`,
            'Content-Type': 'application/json'
          },
          data: {
            inputs: {},
            query: query,
            response_mode: 'blocking',
            conversation_id: '',
            user: 'user-123',
            files: []
          },
          dataType: 'json',
          success: (res) => {
            // 处理响应
            if (res.statusCode === 200) {
              const response = res.data;
              
              if (response && response.answer) {
                // 添加AI回复
                this.messages.push({
                  role: 'assistant',
                  content: response.answer
                });
              } else {
                // 错误处理
                this.messages.push({
                  role: 'assistant',
                  content: '抱歉，我无法处理您的请求。'
                });
              }
            } else {
              // HTTP错误处理
              this.messages.push({
                role: 'assistant',
                content: `请求错误: ${res.statusCode}`
              });
            }
          },
          fail: (err) => {
            console.error('API调用错误:', err);
            this.messages.push({
              role: 'assistant',
              content: '网络错误，请稍后再试。'
            });
          },
          complete: () => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.scrollToBottom();
              // 也滚动页面到底部
              this.scrollPageToBottom();
            });
          }
        });
      } catch (error) {
        console.error('API调用异常:', error);
        this.messages.push({
          role: 'assistant',
          content: '发生异常，请稍后再试。'
        });
        this.isLoading = false;
        this.$nextTick(() => {
          this.scrollPageToBottom();
        });
      }
    },
    
    scrollToBottom() {
      // 获取滚动区域的高度并滚动到底部
      const query = uni.createSelectorQuery().in(this);
      query.select('.message-area').boundingClientRect();
      query.exec(res => {
        if (res && res[0]) {
          this.scrollTop = res[0].height * 100; // 确保滚动到底部
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-chat-page {
  margin-top: 20rpx;
  width: 100%;
  height: 400rpx;
  display: flex;
  flex-direction: column;
  transition: height 0.3s ease;
  
  &.expanded {
    height: 1000rpx;
    .section-title {
      margin-bottom: 20rpx;
    }
  }
  
  .section-title { 
    margin-top: 20rpx;
    padding: 15rpx 0;
    text-align: center;
    background: linear-gradient(90deg, rgba(0,103,255,0.1) 0%, rgba(0,103,255,0.3) 50%, rgba(0,103,255,0.1) 100%);
    border-radius: 8rpx;
    margin-bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: margin-bottom 0.3s ease;
    
    .logo-image {
      width: 150rpx;
      height: 42rpx;
      object-fit: contain;
    }
  }
  
  .empty-home {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 20rpx 30rpx;
    
    .logo-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 30rpx;
      
      .big-logo {
        width: 350rpx;
        height: 76rpx;
        object-fit: contain;
        margin-bottom: 20rpx;
      }
      
      .slogan {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
    
    .input-area {
      width: 100%;
      display: flex;
      background-color: #fff;
      padding: 16rpx;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
      align-items: center;
      
      .message-input {
        flex: 0.8;
        height: 70rpx;
        border: 1px solid #ddd;
        border-radius: 35rpx;
        padding: 0 25rpx;
        font-size: 26rpx;
        background-color: #f9f9f9;
      }
      
      .send-button {
        margin-left: 16rpx;
        flex: 0.2;
        height: 70rpx;
        padding: 0;
        min-width: 140rpx;
        border-radius: 35rpx;
        background-color: #1C64F2;
        color: #fff;
        font-size: 26rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        white-space: nowrap;
        overflow: hidden;
        
        &[disabled] {
          background-color: #c0d0e9;
        }
      }
    }
  }
  
  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #f7f7f7;
    border-radius: 12rpx;
    overflow: hidden;
    margin: 0 20rpx 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
    
    .message-area {
      flex: 1;
      padding: 20rpx;
      overflow-y: auto;
      max-height: calc(100vh - 300rpx);
      
      .message-item {
        margin-bottom: 16rpx;
        
        &.user {
          display: flex;
          justify-content: flex-end;
          
          .message-content {
            background-color: #1C64F2;
            color: #fff;
            border-radius: 18rpx 18rpx 0 18rpx;
            box-shadow: 0 2rpx 6rpx rgba(28,100,242,0.2);
          }
        }
        
        &.assistant {
          display: flex;
          justify-content: flex-start;
          
          .message-content {
            background-color: #fff;
            color: #333;
            border-radius: 18rpx 18rpx 18rpx 0;
            box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
          }
        }
        
        .message-content {
          padding: 12rpx 20rpx;
          max-width: 85%;
          word-break: break-word;
          line-height: 1.4;
          font-size: 28rpx;
        }
      }
    }
    
    .input-area {
      display: flex;
      padding: 16rpx;
      background-color: #fff;
      border-top: 1px solid #eeeeee;
      align-items: center;
      
      .message-input {
        flex: 0.8;
        height: 70rpx;
        border: 1px solid #ddd;
        border-radius: 35rpx;
        padding: 0 25rpx;
        font-size: 28rpx;
        background-color: #f9f9f9;
      }
      
      .send-button {
        margin-left: 16rpx;
        flex: 0.2;
        height: 70rpx;
        padding: 0;
        min-width: 140rpx;
        border-radius: 35rpx;
        background-color: #1C64F2;
        color: #fff;
        font-size: 26rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        white-space: nowrap;
        overflow: hidden;
        
        &[disabled] {
          background-color: #c0d0e9;
        }
      }
    }
  }
}
</style> 